package com.express.gateway.manage.auth;

import com.express.gateway.common.util.PathUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.ext.auth.authentication.AuthenticationProvider;

import java.util.Objects;

/**
 * 客户端通用权限认证的实现
 *
 * @author flower
 */
public class ClientAuthProviderImpl implements AuthenticationProvider {
    private Vertx vertx;

    public ClientAuthProviderImpl(Vertx vertx) {
        super();
        this.vertx = vertx;
    }

    @Override
    public void authenticate(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
        String username = authInfo.getString("username");
        if (authInfo.getString("username") == null || "".equals(authInfo.getString("username"))) {
            resultHandler.handle(Future.<User>succeededFuture(null));
            return;
        }
        String pwd = authInfo.getString("password");
        String path = PathUtil.getPathString("user.json");
        vertx.fileSystem().readFile(path, res -> {
            if (res.failed()) {
                resultHandler.handle(Future.failedFuture("找不到用户配置文件:" + path));
                return;
            }
            try {
                JsonObject users = res.result().toJsonObject();
                JsonObject user = users.getJsonObject(username);
                if (Objects.isNull(pwd) || !pwd.equals(user.getString("pwd"))) {
                    resultHandler.handle(Future.<User>succeededFuture(null));
                    return;
                }
                User authUser = User.create(new JsonObject().put("roles", user.getJsonArray("roles")));
                resultHandler.handle(Future.<User>succeededFuture(authUser));
            } catch (Exception e) {

                resultHandler.handle(Future.<User>succeededFuture(null));
            }
        });
    }

    public Vertx getVertx() {
        return vertx;
    }

    public void setVertx(Vertx vertx) {
        this.vertx = vertx;
    }

}
